from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login
from django.contrib import messages
from django.contrib.auth import logout


def user_login(request):
    if request.method == 'POST':
        username = request.POST['username']
        password = request.POST['password']
        user = authenticate(request, username=username, password=password)
        if user is not None:
            login(request, user)
            return redirect('home:home')  # 登录成功后跳转到主页
        else:
            messages.error(request, "账号或密码错误")
    return render(request, 'login/login.html')


def logout_view(request):
    logout(request)  # 退出用户
    return redirect('users:login')
